package com.choudou5.tools.qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;


public class QrCodeUtil {

    // 图片宽度的一半
    private static final int IMAGE_WIDTH = 50;
    private static final int IMAGE_HEIGHT = 50;
    private static final int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2;
    private static final int FRAME_WIDTH = 2;
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    // 二维码写码器
    private static MultiFormatWriter multiWriter = new MultiFormatWriter();


    // 图片宽度的一半

    public static void main(String[] args) throws Exception {
        String url = "https://www.baidu.com/";
        genQrCode(url, Color.PINK, Color.BLUE, "d:\\qrcode11.jpg");
        genQrCode(url, Color.GREEN, Color.BLUE, "d:\\qrcode22.jpg");
        genQrCode(url, Color.ORANGE, Color.BLUE, "d:\\qrcode33.jpg");
        genQrCode(url, Color.RED, Color.BLUE, "d:\\qrcode44.jpg");
    }

    private static void genQrCode(String url, Color left, Color right, String toPath) throws Exception {
//        String logoPath ="d:\\logo.png";
        BufferedImage image5 = genQrcode(url, 300, 300);
        Color[] gradientcolors = getGradientColor(left, right,30);
        BufferedImage resImg5 = handleGradientQRCodeOblique(image5, gradientcolors);
        ImageIO.write(resImg5, "png", new File(toPath));
    }

    /**
     * 生成二维码图片文件（不带LOGO）
     * @param content 要生成二维码的内容
     * @param width   二维码的高度
     * @param height  二维码的宽度
     * @return 二维码图片
     * @throws WriterException 异常
     */
    private static BufferedImage genQrcode(String content, int width, int height) throws WriterException {
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //根据高度和宽度生成像素矩阵
        BitMatrix bitMatrix = multiWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                //填充黑白两色
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }

        return image;
    }


    /**
     * 生成二维码图片文件（带LOGO）
     * @param content      要生成二维码的内容
     * @param width        二维码的宽度
     * @param height       二维码的高度
     * @param srcImagePath 二维码中间logo图片的路径
     * @return 二维码图片
     * @throws WriterException 异常
     * @throws IOException     异常
     */
    private static BufferedImage genQrcodeWithLogo(String content, int width,
                                                   int height, String srcImagePath) throws WriterException, IOException {
        // 读取源图像并拆分成像素点
        BufferedImage scaleImage = scale(srcImagePath, IMAGE_WIDTH, IMAGE_HEIGHT, true);
        int[][] srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];
        for (int i = 0; i < scaleImage.getWidth(); i++) {
            for (int j = 0; j < scaleImage.getHeight(); j++) {
                srcPixels[i][j] = scaleImage.getRGB(i, j);//图片的像素点
            }
        }
        //编码
        Map hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置容错等级，在这里我们使用M级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 生成二维码
        BitMatrix matrix = multiWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        // 二维矩阵转为一维像素数组
        int halfW = matrix.getWidth() / 2;
        int halfH = matrix.getHeight() / 2;
        int[] pixels = new int[width * height];
        for (int y = 0; y < matrix.getHeight(); y++) {
            for (int x = 0; x < matrix.getWidth(); x++) {
                // 左上角颜色,根据自己需要调整颜色范围和颜色
                if (x > 0 && x < 170 && y > 0 && y < 170) {
                    Color color = new Color(231, 144, 56);
                    int colorInt = color.getRGB();
                    pixels[y * width + x] = matrix.get(x, y) ? colorInt : 16777215;
                } else
                    // 将Logo图片的像素点填充到二维码中间区域
                    if (x > halfW - IMAGE_HALF_WIDTH
                            && x < halfW + IMAGE_HALF_WIDTH
                            && y > halfH - IMAGE_HALF_WIDTH
                            && y < halfH + IMAGE_HALF_WIDTH) {
                        pixels[y * width + x] = srcPixels[x - halfW + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
                    }
                    // 在图片四周形成边框
                    else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH
                            && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)
                            || (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
                            && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)
                            || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
                            && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH - IMAGE_HALF_WIDTH + FRAME_WIDTH)
                            || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
                            && y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)) {
                        pixels[y * width + x] = 0xfffffff;
                    } else {
                        if (matrix.get(x, y)) {
//                            //生成4色
//                            if (x < width / 2 && y < height / 2) {
//                                pixels[y * width + x] = 0xFF0094FF;// 蓝色
//                                Integer.toHexString(new Random().nextInt());
//                            } else if (x < width / 2 && y > height / 2) {
//                                pixels[y * width + x] = 0xFFFED545;// 黄色
//                            } else if (x > width / 2 && y > height / 2) {
//                                pixels[y * width + x] = 0xFF5ACF00;// 绿色
//                            } else {
//                                pixels[y * width + x] = 0xFF000000;// 黑色
//                            }

                            //生成渐变色
                            if (x < width / 2) {
                                int num1 = (int) (255 - (255.0 - 120.0) / matrix.getHeight() * (matrix.getHeight() - y));
                                int num2 = (int) (0 - (0.0 - 0.0) / matrix.getHeight() * (matrix.getHeight() - y));
                                int num3 = (int) (0 - (0.0 - 0.0) / matrix.getHeight() * (matrix.getHeight() - y));
                                Color color = new Color(num1, num2, num3);
                                int colorInt = color.getRGB();
                                // 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
                                pixels[y * width + x] = matrix.get(x, y) ? colorInt : 0xFF000000;// 0x000000:0xffffff
                            } else {
                                int num1 = (int) (0 - (0.0 - 0.0) / matrix.getHeight() * (matrix.getHeight() - y));
                                int num2 = (int) (0 - (0.0 - 0.0) / matrix.getHeight() * (matrix.getHeight() - y));
                                int num3 = (int) (255 - (255.0 - 120.0) / matrix.getHeight() * (matrix.getHeight() - y));
                                Color color = new Color(num1, num2, num3);
                                int colorInt = color.getRGB();
                                // 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
                                pixels[y * width + x] = matrix.get(x, y) ? colorInt : 0xFF000000;// 0x000000:0xffffff
                            }
                        } else {
                            pixels[y * width + x] = -1;  //白色
                        }
                    }
            }
        }
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        image.getRaster().setDataElements(0, 0, width, height, pixels);
        return image;
    }

    /**
     * 把传入的原始图像按高度和宽度进行缩放，生成符合要求的图标
     * @param srcImageFile 源文件地址
     * @param height       目标高度
     * @param width        目标宽度
     * @param hasFiller    比例不对时是否需要补白：true为补白; false为不补白;
     * @throws IOException
     */
    private static BufferedImage scale(String srcImageFile, int height, int width, boolean hasFiller) throws IOException {
        double ratio = 0.0; // 缩放比例
        BufferedImage srcImage = ImageIO.read(new File(srcImageFile));
        Image destImage = srcImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
        // 计算比例
        if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
            if (srcImage.getHeight() > srcImage.getWidth()) {
                ratio = (new Integer(height)).doubleValue() / srcImage.getHeight();
            } else {
                ratio = (new Integer(width)).doubleValue() / srcImage.getWidth();
            }
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
            destImage = op.filter(srcImage, null);
        }
        if (hasFiller) {// 补白
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphic = image.createGraphics();
            graphic.setColor(Color.white);
            graphic.fillRect(0, 0, width, height);
            if (width == destImage.getWidth(null)) {
                graphic.drawImage(destImage, 0,
                        (height - destImage.getHeight(null)) / 2,
                        destImage.getWidth(null), destImage.getHeight(null),
                        Color.white, null);//画图片
            } else {
                graphic.drawImage(destImage,
                        (width - destImage.getWidth(null)) / 2, 0,
                        destImage.getWidth(null), destImage.getHeight(null),
                        Color.white, null);
            }
            graphic.dispose();
            destImage = image;
        }
        return (BufferedImage) destImage;
    }



    /**
     * 生成一个上下左右四个方块颜色不同的二维码
     * @param image 待处理的二维码图片
     * @param leftTopColor 左上角颜色
     * @param leftBottomColor 左下角颜色
     * @param rightTopColor 右上角颜色
     * @param rightBottomColor 右下角颜色
     * @return 处理后的二维码
     */
    public static BufferedImage handleGradientQRCodeBlock(BufferedImage image, Color leftTopColor, Color leftBottomColor, Color rightTopColor, Color rightBottomColor){
        image = convertToARGB(image);
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                int  clr   = image.getRGB(x, y);
                int  red   = (clr & 0x00ff0000) >> 16;
                int  green = (clr & 0x0000ff00) >> 8;
                int  blue  =  clr & 0x000000ff;
                if(red < 50 && green < 50 && blue < 50){
                    Color fillColor;
                    if(x < image.getWidth() / 2){
                        if(y < image.getHeight() / 2){
                            //左上
                            fillColor = leftTopColor;
                        }else{
                            //左下
                            fillColor = leftBottomColor;
                        }

                    }else{
                        if(y < image.getHeight() / 2){
                            //右上
                            fillColor = rightTopColor;
                        }else{
                            //右下
                            fillColor = rightBottomColor;
                        }
                    }
                    image.setRGB(x,y,fillColor.getRGB());
                }

            }
        }
        return image;
    }

    /**
     * 生成一个每一行颜色不同的二维码
     * @param image 待处理的二维码
     * @param colors 每一行的颜色
     * @return 处理后的二维码
     */
    public static BufferedImage handleGradientQRCodeRow(BufferedImage image, Color[] colors){
        image = convertToARGB(image);
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                int clr = image.getRGB(x, y);
                int red = (clr & 0x00ff0000) >> 16;
                int green = (clr & 0x0000ff00) >> 8;
                int blue = clr & 0x000000ff;
                if (red < 50 && green < 50 && blue < 50) {
                    int step = image.getWidth() / colors.length;
                    int currentStep = y / step;
                    if(currentStep >= colors.length){
                        currentStep =  colors.length - 1;
                    }
                    Color currentColor = colors[currentStep];
                    image.setRGB(x,y,currentColor.getRGB());
                }
            }

        }
        return image;
    }

    /**
     * 生成一个每一列颜色不同的二维码
     * @param image 待处理的二维码
     * @param colors 每一列的颜色
     * @return 处理后的二维码
     */
    public static BufferedImage handleGradientQRCodeColoum(BufferedImage image, Color[] colors){
        image = convertToARGB(image);
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                int clr = image.getRGB(x, y);
                int red = (clr & 0x00ff0000) >> 16;
                int green = (clr & 0x0000ff00) >> 8;
                int blue = clr & 0x000000ff;
                if (red < 50 && green < 50 && blue < 50) {
                    int step = image.getWidth() / colors.length;
                    int currentStep = x / step;
                    if(currentStep >= colors.length){
                        currentStep =  colors.length - 1;
                    }
                    Color currentColor = colors[currentStep];
                    image.setRGB(x,y,currentColor.getRGB());
                }
            }

        }
        return image;
    }

    /**
     * 生成一个每一对角线颜色不同的二维码
     * @param image 待处理的二维码
     * @param colors 每一对角线的颜色
     * @return 处理后的二维码
     */
    public static BufferedImage handleGradientQRCodeOblique(BufferedImage image, Color[] colors){
        image = convertToARGB(image);
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                int clr = image.getRGB(x, y);
                int red = (clr & 0x00ff0000) >> 16;
                int green = (clr & 0x0000ff00) >> 8;
                int blue = clr & 0x000000ff;
                if (red < 50 && green < 50 && blue < 50) {
                    int currentStep = 0;
                    for(int i = 0; i < colors.length; i++){
                        if((x + y) - ((i + 1) * 2.0 * image.getWidth()) / (colors.length)  < 0){
                            currentStep  = i;
                            break;
                        }
                    }
                    Color currentColor;
                    currentColor = colors[currentStep];
                    image.setRGB(x,y,currentColor.getRGB());
                }
            }
        }
        return image;
    }

    /**
     * 生成一个每一对角线颜色不同的二维码(反向)
     * @param image 待处理的二维码
     * @param colors 每一对角线的颜色
     * @return 处理后的二维码
     */
    public static BufferedImage handleGradientQRCodeObliqueReverse(BufferedImage image, Color[] colors){
        image = convertToARGB(image);
        for (int y = 0; y < image.getHeight(); y++) {
            for (int x = 0; x < image.getWidth(); x++) {
                int clr = image.getRGB(x, y);
                int red = (clr & 0x00ff0000) >> 16;
                int green = (clr & 0x0000ff00) >> 8;
                int blue = clr & 0x000000ff;
                if (red < 50 && green < 50 && blue < 50) {
                    int currentStep = 0;
                    for(int i = 0; i < colors.length; i++){
                        if((y - x) + ((i - 1) * 2.0 * image.getWidth()) / (colors.length)  > 0){
                            currentStep  = i;
                            break;
                        }
                    }
                    Color currentColor;
                    currentColor = colors[currentStep];

                    image.setRGB(x,y,currentColor.getRGB());
                }
            }

        }
        return image;
    }


    public static Color[] getGradientColor(Color fromColor, Color toColor, int step){
        ArrayList<Color> colorList = new ArrayList<Color>();
        int fromR = fromColor.getRed();
        int fromG = fromColor.getGreen();
        int fromB = fromColor.getBlue();
        int toR = toColor.getRed();
        int toG = toColor.getGreen();
        int toB = toColor.getBlue();
        for(int i = 0; i < step; i++){
            int r = fromR + (toR - fromR) / step * i;
            int g = fromG + (toG - fromG) / step * i;
            int b = fromB + (toB - fromB) / step * i;
            Color color = new Color(r,g,b);
            colorList.add(color);
        }
        return colorList.toArray(new Color[step]);
    }

    private static BufferedImage convertToARGB(BufferedImage image) {

        if (image.getType() == BufferedImage.TYPE_INT_ARGB) {
            return image;
        }

        BufferedImage newImage = new BufferedImage(
                image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = newImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return newImage;
    }

}
